package com.hunan.api.catv.service.biz.tencent_cloud.vod;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.FilesStateEnum;
import com.hunan.api.catv.entity.enums.FilesTypeEnum;
import com.hunan.api.catv.entity.enums.VideoDefinitionEnum;
import com.hunan.api.catv.entity.po.Files;
import com.hunan.api.catv.entity.po.News;
import com.hunan.api.catv.entity.vo.FilesVo;
import com.hunan.api.catv.service.biz.activity.ActivityVideoBiz;
import com.hunan.api.catv.service.biz.files.FilesBiz;
import com.hunan.api.catv.service.biz.news.NewsBiz;
import com.hunan.api.catv.service.impl.news.NewsService;
import com.hunan.api.catv.utils.FileUtils;
import com.hunan.api.catv.utils.GsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class NotifyBiz {

    private static final Logger LOGGER = LoggerFactory.getLogger(NotifyBiz.class);


    @Autowired
    FilesBiz filesBiz;

    @Autowired
    ActivityVideoBiz activityVideoBiz;

    @Autowired
    NewsBiz newsBiz;

    @Autowired
    private NewsService newsService;

    public boolean notify(JsonObject body) {
        String eventType = body.get("EventType").getAsString();
        if ("NewFileUpload".equals(eventType)) {
            JsonObject fileUploadEvent = body.getAsJsonObject("FileUploadEvent");
            String fileId = fileUploadEvent.get("FileId").getAsString();
            String baseUrl = fileUploadEvent.getAsJsonObject("MediaBasicInfo").get("MediaUrl").getAsString();
            String width = fileUploadEvent.getAsJsonObject("MetaData").get("Width").getAsString();
            String height = fileUploadEvent.getAsJsonObject("MetaData").get("Height").getAsString();
            String size = FileUtils.convertFileSize(Long.valueOf(fileUploadEvent.getAsJsonObject("MetaData").get("Size").getAsString()));
            String duration = fileUploadEvent.getAsJsonObject("MetaData").get("AudioDuration").getAsString();
            JsonObject urlInfo = new JsonObject();
            JsonObject basic = new JsonObject();
            basic.addProperty("url", baseUrl);
            basic.addProperty("width", width);
            basic.addProperty("height", height);
            urlInfo.add("basic", basic);
            FilesVo filesVo = filesBiz.getByFileId(fileId);
            Files files = new Files();
            files.setFileId(fileId);
            files.setUrl(urlInfo.toString());
            files.setSize(size);
            files.setDuration(duration);
            files.setState(FilesStateEnum.process.getCode());
            files.setType(FilesTypeEnum.video.getCode());
            if (ObjectUtils.isEmpty(filesVo)) {
                filesBiz.add(files);
            } else {
                files.setfId(filesVo.getfId());
                filesBiz.update(files);
            }
            //修改用户上传短视频
            updateNews(fileId, files);
        }
        if ("ProcedureStateChanged".equals(eventType)) {
            JsonObject procedureStateChangeEvent = body.getAsJsonObject("ProcedureStateChangeEvent");
            String fileId = procedureStateChangeEvent.get("FileId").getAsString();
            FilesVo filesVo = filesBiz.getByFileId(fileId);
            if (!ObjectUtils.isEmpty(filesVo)) {
                Files files = getFilesInfo(filesVo, procedureStateChangeEvent);
				/*JsonObject urlInfo = GsonUtils.fromJson(filesVo.getUrl(), JsonObject.class);
				JsonArray mediaProcessResultSet = procedureStateChangeEvent.getAsJsonArray("MediaProcessResultSet");
				for (int i = 0; i < mediaProcessResultSet.size(); i++) {
					JsonObject media = mediaProcessResultSet.get(i).getAsJsonObject();
					String type = media.get("Type").getAsString();
					if("Transcode".equals(type)) {
						JsonObject transcodeTask = media.getAsJsonObject("TranscodeTask");
						JsonObject output = transcodeTask.getAsJsonObject("Output");
						String url = output.get("Url").getAsString();
						String width = output.get("Width").getAsString();
						String height = output.get("Height").getAsString();
						String definition = output.get("Definition").getAsString();
						JsonObject mediaInfo = new JsonObject();
						mediaInfo.addProperty("url", url);
						mediaInfo.addProperty("width", width);
						mediaInfo.addProperty("height", height);
						urlInfo.add(VideoDefinitionEnum.getValue(definition), mediaInfo);
					}
					if("CoverBySnapshot".equals(type)) {
						JsonObject coverBySnapshotTask = media.getAsJsonObject("CoverBySnapshotTask");
						JsonObject coverOutput = coverBySnapshotTask.getAsJsonObject("Output");
						cover = coverOutput.get("CoverUrl").getAsString();
					}
				}
				Files files = new Files();
				files.setfId(filesVo.getfId());
				files.setUrl(urlInfo.toString());
				files.setState(FilesStateEnum.normal.getCode());
				files.setDetail(procedureStateChangeEvent.toString());
				if(ObjectUtils.isEmpty(filesVo.getCover())) {
					files.setCover(cover);
				}*/
                ServiceResult updateResule = filesBiz.update(files);
                if (updateResule.getStatus() && filesVo.getIsActivity() == 1) {
                    activityVideoBiz.editState(fileId, FilesStateEnum.under_audit.getCode());
                }

				/*List<News> newsList = new News().selectList(new QueryWrapper<News>().eq(News.FILEID, fileId).eq(News.VIDEO_SOURCE, 1));
				if(CollectionUtils.isNotEmpty(newsList)){
					for (News news : newsList) {
						FilesVo filesVo1 = new FilesVo();
						BeanUtils.copyProperties(news,filesVo1);
						files = getFilesInfo(filesVo1, procedureStateChangeEvent);
						news.setUrl(files.getUrl());
						news.updateById();
						//修改用户上传短视频
						//updateNews(fileId,files);
					}
				}*/
                News news = newsBiz.getNewsInfoByFileId(fileId);
                if (news != null) {
                    FilesVo filesVo1 = new FilesVo();
                    BeanUtils.copyProperties(news, filesVo1);
                    files = getFilesInfo(filesVo1, procedureStateChangeEvent);
                    news.setUrl(files.getUrl());
                    LOGGER.info("回调地址:{}", files.getUrl());
                    newsService.updateNewUrl(news);
                    //ServiceResult update = newsBiz.update(news);
                    LOGGER.info("用户发布短视频回调更改路径:{},查询参数:{}", news);
                    //修改用户上传短视频
                }
            }
        }
        return true;
    }

    private Files getFilesInfo(FilesVo filesVo, JsonObject procedureStateChangeEvent) {
        String cover = "";
        JsonObject urlInfo = GsonUtils.fromJson(filesVo.getUrl(), JsonObject.class);
        urlInfo = (null == urlInfo ? new JsonObject() : urlInfo);
        JsonArray mediaProcessResultSet = procedureStateChangeEvent.getAsJsonArray("MediaProcessResultSet");
        for (int i = 0; i < mediaProcessResultSet.size(); i++) {
            JsonObject media = mediaProcessResultSet.get(i).getAsJsonObject();
            String type = media.get("Type").getAsString();
            if ("Transcode".equals(type)) {
                JsonObject transcodeTask = media.getAsJsonObject("TranscodeTask");
                JsonObject output = transcodeTask.getAsJsonObject("Output");
                String url = output.get("Url").getAsString();
                String width = output.get("Width").getAsString();
                String height = output.get("Height").getAsString();
                String definition = output.get("Definition").getAsString();
                JsonObject mediaInfo = new JsonObject();
                mediaInfo.addProperty("url", url);
                mediaInfo.addProperty("width", width);
                mediaInfo.addProperty("height", height);
                urlInfo.add(VideoDefinitionEnum.getValue(definition), mediaInfo);
            }
            if ("CoverBySnapshot".equals(type)) {
                JsonObject coverBySnapshotTask = media.getAsJsonObject("CoverBySnapshotTask");
                JsonObject coverOutput = coverBySnapshotTask.getAsJsonObject("Output");
                cover = coverOutput.get("CoverUrl").getAsString();
            }
        }
        Files files = new Files();
        files.setfId(filesVo.getfId());
        files.setUrl(urlInfo.toString());
        files.setState(FilesStateEnum.normal.getCode());
        files.setDetail(procedureStateChangeEvent.toString());
        if (ObjectUtils.isEmpty(filesVo.getCover())) {
            files.setCover(cover);
        }
        return files;
    }

    /**
     * 修改用户上传短视频
     */
    private void updateNews(String fileId, Files files) {
        //查询用户上传短视频
        List<News> newsList = new News().selectList(new QueryWrapper<News>().eq(News.FILEID, fileId).eq(News.VIDEO_SOURCE, 1));
        newsList = newsList.parallelStream().map(news -> {
            BeanUtils.copyProperties(files, news);
            news.setPicMinivideo(StringUtils.isNotBlank(news.getPicMinivideo()) ? news.getPicMinivideo() : files.getCover());
            news.setUrl(files.getUrl());
            news.setFileSize(files.getSize());
            news.setNewsType(2);
            //待腾讯云审核
            news.setState(7);
            news.updateById();
            return news;
        }).collect(Collectors.toList());
    }
}
